package view;

import java.awt.Container;import java.awt.FlowLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.DataInputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.InputStream;import java.io.InputStreamReader;
import java.util.Vector;

import javax.swing.AbstractAction;import javax.swing.JComboBox;import javax.swing.JComponent;import javax.swing.JLabel;import javax.swing.JTextField;import javax.swing.KeyStroke;import javax.swing.RowFilter;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;import javax.swing.table.TableRowSorter;

import model.Employee;import net.miginfocom.swing.MigLayout;

/**
 * Employees panel in the manager's view
 * @author dan
 *
 */
public class EmployeesPanel extends JPanel{	private static final long serialVersionUID = 1L;	private Vector<Object[]> data;	private String[] headers = {"Name", "Department", "Contact", "Title"};	private JTable table;	private Vector<Employee> employees;	private JComboBox filterbox;	//private JComboBox departmentfilter;	private JTextField textfilter;	private JButton filterbutton;	private JButton clearbutton;
	/**
	 * Constructor
	 */
	public EmployeesPanel(){		employees = new Vector<Employee>();		loadEmployees();
		data = loadTableData();
		initGUI();
	}
	/**
	 * Initializes and sets up all GUI elements
	 */
	private void initGUI(){		this.setLayout(new MigLayout("fillx,insets 25"));  
		table = new JTable();		table.addMouseListener(new MouseHandler());		table.setAutoCreateRowSorter(true);		TableModel model = new TableModel();		table.setModel(model);		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);				filterbox = new JComboBox(new String[]{"Name","Title","Department"});		//departmentfilter = new JComboBox(new String[]{"Reception","Room Service","House Keeping", "Kitchen", "Mantainence","Security"});		textfilter = new JTextField(8);				JPanel panel = new JPanel(new FlowLayout());				panel.add(new JLabel("Filter: "));		panel.add(filterbox);		panel.add(textfilter);		//panel.add(departmentfilter);		filterbutton = new JButton(new ButtonAction("Filter"));		clearbutton = new JButton(new ButtonAction("Clear"));		panel.add(filterbutton);		panel.add(clearbutton,"wrap");		//departmentfilter.setVisible(false);		//textfilter.setVisible(false);		this.add(panel,"wrap");				//filterbox.addActionListener(new FilterListener());		
		JScrollPane scrollPane = new JScrollPane(table);		scrollPane.setPreferredSize(new Dimension(this.getMaximumSize().width - 50, this.getMaximumSize().height - 200));		table.setFillsViewportHeight(true);		this.add(scrollPane,"span");		
		this.add(new JButton(new ButtonAction("Add Employee")),"split 2");		this.add(new JButton(new ButtonAction("Delete Employee")));			KeyStroke delete = KeyStroke.getKeyStroke("DELETE");		table.registerKeyboardAction(new ButtonAction("Delete Employee"), delete, JComponent.WHEN_FOCUSED);	}	/**	 * loads data from employees vector into another vector to be displayed by the table	 * @return	 */
	private Vector<Object[]> loadTableData(){		Vector<Object[]> v = new Vector<Object[]>();				for(Employee e : employees){			v.add(new Object[]{e.getName(), e.getDepartment(), e.getEmail(), e.getTitle()});		}		return v;			}	/**	 * save employee data to employees.txt	 */	private void saveEmployees(){		try{			FileWriter fs = new FileWriter("employees.txt");			BufferedWriter out = new BufferedWriter(fs);			for(Employee emp : employees){				String s = emp.toString();				out.write(s);				out.write("\n");			}			out.close();		}		catch(Exception e){			e.printStackTrace();		}	}
	/**
	 * Load all employee data from employees.txt
	 * @return 
	 */
	private void loadEmployees(){		FileInputStream fs;		DataInputStream ds;		BufferedReader br;		try {			fs = new FileInputStream("employees.txt");			ds = new DataInputStream(fs);			br = new BufferedReader(new InputStreamReader(ds));						String str;			while((str = br.readLine()) != null){				String[] att = str.split("\\+");				Employee emp = new Employee(att[0],att[1],att[2],att[3],att[4],att[5],att[6],att[7],att[8],att[9],Float.valueOf(att[10]));				employees.add(emp);			}		} catch (Exception e) {			// TODO Auto-generated catch block			e.printStackTrace();		}
	}	/**	 * remove an employee from the employees vector by employee name	 * @param name	 */
	private void deleteEmployee(String name){		for(int i=0; i<employees.size();i++){			if(employees.get(i).getName().equals(name)){				employees.remove(i);				return;			}		}	}	/**	 * add an employee to the employees vector, delete the old one if it's a duplicate	 * @param emp	 */	public void addEmployee(Employee emp){		deleteEmployee(emp.getName());				employees.add(emp);		data = loadTableData();		table.setModel(new TableModel());		table.repaint();		filterbutton.doClick();				saveEmployees();	}	/**	 * returns the employee object for a person's name	 * @param name	 * @return	 */	private Employee getEmployee(String name){		for(int i=0; i<employees.size();i++){			if(employees.get(i).getName().equals(name)){				return employees.get(i);			}		}		return null;	}
	/**
	 * handle all button actions
	 * @author dan
	 *
	 */
	
	private class ButtonAction extends AbstractAction { 
		private static final long serialVersionUID = 1L;		
		public ButtonAction(String name) {			putValue(Action.NAME, name); 		}				public void actionPerformed(ActionEvent event) { 			String name = (String)getValue(Action.NAME);			if(name.equals("Add Employee")){				Employee emp = new Employee();
				EmployeeDialog ep = new EmployeeDialog(EmployeesPanel.this, emp);
				ep.setVisible(true);			}			else if(name.equals("Delete Employee")){				int row = table.getSelectedRow();				int col = table.getSelectedColumn();				
				if(row == -1 || col == -1) return;							row = table.convertRowIndexToModel(row);				col = table.convertColumnIndexToModel(col);
				int ans = JOptionPane.showConfirmDialog(EmployeesPanel.this, "Are you sure you want to delete this employee?","Delete?",JOptionPane.YES_NO_OPTION);
				if(ans == JOptionPane.YES_OPTION){					String empName = (String)data.get(row)[0];
					deleteEmployee(empName);					data = loadTableData();
					table.setModel(new TableModel());					table.repaint();					filterbutton.doClick();										saveEmployees();				}			}			else if(name.equals("Filter")){				String filter = (String)filterbox.getSelectedItem();				int col = -1;				for(int i=0; i<headers.length; i++){					if(headers[i].equals(filter)){						col = i;						break;					}				}								data = loadTableData();				if(col != -1){					String text = textfilter.getText();					for(int i=0; i<data.size(); i++){						if(!data.get(i)[col].toString().toLowerCase().contains(text.toLowerCase())){							data.remove(i);							i--;						}					}				}				table.setModel(new TableModel());				textfilter.requestFocus();				table.repaint();							}			else if(name.equals("Clear")){				textfilter.setText("");				filterbutton.doClick();				textfilter.requestFocus();			}		}
	}
	/**
	 * Default table model but all cells are not editable
	 * @author dan
	 *
	 */
	class TableModel extends AbstractTableModel {
		public int getColumnCount() {			return headers.length;		}		public int getRowCount() {			return data.size();		}
		public String getColumnName(int col) {			return headers[col];		}		public Object getValueAt(int row, int col) {			return data.get(row)[col];		}
		public boolean isCellEditable(int row, int col) {			return false;		}	}
	
	public class MouseHandler implements MouseListener{
		public void mouseClicked(MouseEvent arg0) {
			if(arg0.getClickCount() >= 2){					int row = table.getSelectedRow();				int col = table.getSelectedColumn();				if(row == -1 || col == -1) return;				row = table.convertRowIndexToModel(row);				col = table.convertColumnIndexToModel(col);								String name = (String)data.get(row)[0];				Employee emp = getEmployee(name);								EmployeeDialog ed = new EmployeeDialog(EmployeesPanel.this, emp);				ed.setVisible(true);
			}
		}

		public void mouseEntered(MouseEvent arg0) {			// TODO Auto-generated method stub		}
		public void mouseExited(MouseEvent arg0) {			// TODO Auto-generated method stub
		}
		public void mousePressed(MouseEvent arg0) {			// TODO Auto-generated method stub
		}
		public void mouseReleased(MouseEvent arg0) {			// TODO Auto-generated method stub		}	}/*	private class FilterListener implements ActionListener{		@Override		public void actionPerformed(ActionEvent e) {			String filter = (String)filterbox.getSelectedItem();						if(filter.equals("Name")){				departmentfilter.setVisible(false);				textfilter.setVisible(true);			}			else if(filter.equals("Department")){				textfilter.setVisible(false);				departmentfilter.setVisible(true);			}			else if(filter.equals("Title")){				departmentfilter.setVisible(false);				textfilter.setVisible(true);			}			else if(filter.equals("None")){				departmentfilter.setVisible(false);				textfilter.setVisible(false);			}		}			}	*/
	public static void main(String...args){
		JFrame f = new JFrame();
		f.setSize(new Dimension(700,500));
		f.add(new EmployeesPanel());
		f.setVisible(true);
	}
}
